//
//  Api.swift
//  JWBaseLib
//
//  Created by 周季伟 on 2017/12/13.
//  Copyright © 2017年 周季伟. All rights reserved.
//

import Alamofire
import SwiftyJSON

open class Api {
    private var requestIndexList = [RequestIndex]()
    public var isCancelAllWhenDeinit = true
    public init() {
    }
    deinit {
        if isCancelAllWhenDeinit {
            cancelAll()
        }
    }
    open func request(urlString: String,
                      method: HTTPMethod = .get,
                      parameters: [String: Any]? = nil,
                      encoding: ParameterEncoding = URLEncoding.default,
                      headers: [String: String]? = nil,
                      cache: Bool = false,
                      completion: ((ApiResult<JSON>) -> Void)?) {
        if cache {
            let apiResult = ApiManager.shared.loadCache(urlString: urlString, method: method, parameters: parameters, headers: headers)
            completion?(apiResult)
        } else {
            let requestIndex = ApiManager.shared.request(urlString: urlString, method: method, parameters: parameters, encoding: encoding, headers: headers, completion:  completion)
            requestIndexList.append(requestIndex)
        }
    }
    public func cancel(at requestIndex: RequestIndex) {
        ApiManager.shared.cancel(at: requestIndex)
        if let index = requestIndexList.index(of: requestIndex) {
            requestIndexList.remove(at: index)
        }
    }
    public func cancelAll() {
        ApiManager.shared.cancel(some: requestIndexList)
        requestIndexList.removeAll()
    }
}
